﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CodeAngel.UI.Extensions
{
    public static class ListBoxExtensions
    {

        #region ListBox

        /// <summary>
        /// Gets the list box item under the mouse, if there is one.
        /// </summary>
        /// <remarks>Do not use this method if there is a drag/drop operation occuring.</remarks>
        /// <param name="listBox">The list box.</param>
        /// <returns>The list box item under the mouse: null if the mouse is not over a list box item.</returns>
        public static ListBoxItem GetItemUnderMouse(this ListBox listBox)
        {
            Point position = Mouse.GetPosition(listBox);
            var frameworkElementAtPoint = listBox.InputHitTest(position) as FrameworkElement;
            if (frameworkElementAtPoint != null)
            {
                return frameworkElementAtPoint.FindFirstAncestorOfType<ListBoxItem>();
            }

            return null;
        }

        /// <summary>
        /// Gets the list box item under the mouse, if there is one.
        /// </summary>
        /// <remarks>Use this method if there is a drag/drop operation occuring.</remarks>
        /// <param name="listBox">The list box.</param>
        /// <param name="e">Drag event args.</param>
        /// <returns>The list box item under the mouse: null if the mouse is not over a list box item.</returns>
        public static ListBoxItem GetItemUnderMouse(this ListBox listBox, DragEventArgs e)
        {
            Point position = e.GetPosition(listBox);
            var frameworkElementAtPoint = listBox.InputHitTest(position) as FrameworkElement;
            if (frameworkElementAtPoint != null)
            {
                return frameworkElementAtPoint.FindFirstAncestorOfType<ListBoxItem>();
            }

            return null;
        }

        #endregion

    }
}
